﻿using System.Drawing;
using AutoMapper;
using Morin.Services;
using Morin.Shared.Configs;
using Morin.Shared.Models;
using Morin.Shared.Parameters;
using Morin.Wpf.Adapters;
using Morin.Wpf.Common;
using Morin.Wpf.Messages.Players;
using Morin.Wpf.ViewModels.Players;
using Stylet;
using System.IO;
using PropertyChanged;
using IContainer = StyletIoC.IContainer;

namespace Morin.Wpf.ViewModels.Videos;
public class VideoViewModel(
    IApiService apiService,
    IContainer container,
    IWindowManager windowManager,
    IEventAggregator eventAggregator,
    IAppService appService,
    ISourceProtocolAdapter sourceProtocolAdapter,
    AppSettingsConfig appSettingsConfig,
    IMapper mapper) : Conductor<Screen>
{
    private ClassModel? _secondaryClassItem;

    public ClassModel? SecondaryClassItem
    {
        get => _secondaryClassItem;
        set
        {
            _secondaryClassItem = value;
            ClassLastSelectedItem = value;
        }
    }

    private ClassModel? _primaryClassItem;

    public ClassModel? PrimaryClassItem
    {
        get => _primaryClassItem;
        set
        {
            _primaryClassItem = value;
            if (MediaSourceItem != null)
            {
                var classes = appService.GetClasses(MediaSourceItem.Id);
                if (!classes.Any()) return;
                SecondaryClasses = [.. classes.Where(x => value != null && x.Pid == value.Id)];
            }

            //  二级菜单为空的状态
            if (SecondaryClasses is { Count: 0 }) ClassLastSelectedItem = value;
        }
    }

    private ClassModel? _classLastSelectedItem;

    /// <summary>
    /// 主要为防止二菜单为空的情况
    /// </summary>
    public ClassModel? ClassLastSelectedItem
    {
        get => _classLastSelectedItem;
        set
        {
            _classLastSelectedItem = value;
            OnClassSelectedItemChanged(value);
        }
    }

    public BindableCollection<ClassModel>? PrimaryClasses { get;private set; }
    public BindableCollection<ClassModel>? SecondaryClasses { get;private set; }


    public BindableCollection<VideoModel> Videos { get; set; } = [];

    public VideoModel? VideoItem { get; set; }


    public BindableCollection<MediaSourceModel>? MediaSources { get;private set; }
    private MediaSourceModel? _mediaSourceItem;

    public MediaSourceModel? MediaSourceItem
    {
        get => _mediaSourceItem;
        set
        {
            _mediaSourceItem = value;
            OnMediaSourceItemChanged(value);
        }
    }

    public int PageSize { get; set; }

    public int Total { get; set; }


    private int _pageIndex = 1;

    public int PageIndex
    {
        get => _pageIndex;
        set
        {
            _pageIndex = value;
            OnPageIndexChanged(value);
        }
    }


    protected override void OnInitialActivate()
    {
        base.OnInitialActivate();
        
        CreateDirectories();

        SetMediaSources();
    }


    private async void OnMediaSourceItemChanged(MediaSourceModel? value)
    {
        eventAggregator.Publish(new OnMediaSourceItemChangedMessage { Model = value });

        if (value == null) return;
        var classes = appService.GetClasses(value.Id);
        if (classes.Any())
        {
            //  主菜单
            PrimaryClasses = [.. classes.Where(x => x.Pid == 0)];
        }
        else
        {
            //  拉取采集源的分类列表
            var req = new ReqQryVideoPara { SourceId = value.Id, AcName = "list" };
            var rspData = await apiService.ReqQryVideosAsync(req);

            await Execute.OnUIThreadAsync(() =>
            {
                if (rspData.Classes != null)
                {
                    //  采集源默认赋值
                    rspData.Classes.ForEach(c => c.SourceID = value.Id);
                
                    //  菜单列表
                    appService.ClassesAddOrUpdate(value.Id, rspData.Classes);

                    //  主菜单
                    PrimaryClasses = [.. rspData.Classes.Where(x => x.Pid == 0)];
                }
            });
        }
    }


    public async Task PlayAsync(VideoModel o)
    {
        var req = new ReqQryVideoDetailPara { SourceId = o.VodSourceID, VodIds = $"{o.VodId}", AcName = "detail" };
        var detail = await apiService.ReqQryVideoDetailsAsync(req);

        await Execute.PostToUIThreadAsync(() =>
        {
            var playVm = container.Get<PlayerViewModel>();
            //  播放列表
            var para = mapper.Map<ThinkPhpVideoParsingPara>(detail);
            playVm.PlayDict = sourceProtocolAdapter.GetPlayDict(para);

            windowManager.ShowWindow(playVm);
        });
    }


    private async void OnClassSelectedItemChanged(ClassModel? o)
    {
        //  拉取分类下视频列表
        if (o == null) return;
        var req = new ReqQryVideoPara { SourceId = o.SourceID, ClassId = o.Id, AcName = "videolist" };
        var rspData = await apiService.ReqQryVideosAsync(req);
        if (rspData == null) return;
        if (rspData.Videos == null) return;

        //  清空列表
        Videos?.Clear();
        //  赋值
        Total = rspData.Total;
        PageSize = rspData.PageSize;
        PageIndex = rspData.PageIndex;
        //  赋值
        await Execute.OnUIThreadAsync(() =>
        {
            rspData.Videos.ForEach(x =>
            {
                x.VodSourceID = o.SourceID;
                Videos?.Add(mapper.Map<VideoModel>(x));
            });
        });
    }

    private async void OnPageIndexChanged(int pageIndex)
    {
        if (ClassLastSelectedItem == null) return;
        
        var sourceId = ClassLastSelectedItem.SourceID;
        var clsId = ClassLastSelectedItem.Id;
        
        var req = new ReqQryVideoPara
            { SourceId = sourceId, ClassId = clsId, AcName = "detail", PageIndex = pageIndex };
        
        var rspData = await apiService.ReqQryVideosAsync(req);

        await Execute.OnUIThreadAsync(() =>
        {
            Videos?.Clear();
            rspData.Videos.ForEach(x =>
            {
                x.VodSourceID = sourceId;
                Videos?.Add(mapper.Map<VideoModel>(x));
            });
        });
    }

    private void SetMediaSources()
    {
        var videoSources = appService.GetMediaSources();
        
        if (!videoSources.Any()) return;
        
        MediaSources = [.. videoSources];
        
        //  默认选中
        if (MediaSources.Count > 0) MediaSourceItem = MediaSources[0];
    }

    private void CreateDirectories()
    {
        if (!Directory.Exists(appSettingsConfig.PluginsPath))
            if (appSettingsConfig.PluginsPath != null)
                Directory.CreateDirectory(appSettingsConfig.PluginsPath);
        if (Directory.Exists(appSettingsConfig.FFmpegPath)) return;
        if (appSettingsConfig.FFmpegPath != null)
            Directory.CreateDirectory(appSettingsConfig.FFmpegPath);
    }
}